package com.yjd.bi.etl.user.service;

import java.util.Calendar;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.yjd.bi.etl.comm.BaseService;
import com.yjd.bi.etl.comm.Constants;
import com.yjd.bi.etl.sql.UserInfoSqlConstants;
import com.yjd.bi.etl.sql.UserSqlConstants;
import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.util.BiUtil;
import com.yjd.comm.util.DateUtil;

@Component("loginFrequencyService")
public class LoginFrequencyService extends BaseService {

	/**
	 * 每日登录频率统计
	 * 
	 * @throws Exception
	 */
	public void loginFrequencyAccount() throws Exception {
		BiDatabaseInfoModel model = this.getBiDatabaseInfoModel();
		JdbcTemplate jt = BiUtil.getJdbcTemplate(model);

		// 统计历史数据
		long maxDate = jt.queryForInt(UserInfoSqlConstants.GET_MAX_LOGIN_DATE);

		if (maxDate == 0) {
			// 没有统计过，取网站上线运营的第一天 平台上线时间（2013年12月21日00：00：00）
			maxDate = Constants.INITIALIZATION_TIME;
		} else {
			maxDate = DateUtil.dateStringToTimestamp(maxDate + "",
					DateUtil.PATTERN_yyyyMMdd) + Constants.DAYOFSECOND;
		}

		// 获取当天的0点的时间戳
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		long todayTime = todayStart.getTime().getTime() / 1000L;
		
		while (maxDate  < todayTime ) {
			// 统计前一天的用户数据
			statisticLoginData(maxDate, jt);
			maxDate += Constants.DAYOFSECOND;// 加一天和当前时间比较，如果小于当前时间则继续统计
			
		}
	}

	private void statisticLoginData(long maxDate, JdbcTemplate jt) {
		long beginDate = maxDate;
		long endDate = beginDate + Constants.DAYOFSECOND - 1;
		
		long statistical_date =  Long.parseLong(DateUtil.timestampToDateString(
				beginDate, DateUtil.PATTERN_yyyyMMdd));
		logger.info("statistical_date:"+statistical_date);
		
		int pc_login_account,app_login_account,wap_login_account,login_account;
		
		pc_login_account = jt.queryForInt(UserInfoSqlConstants.GET_PC_LOGIN_ACCOUNT, beginDate, endDate);
		app_login_account = jt.queryForInt(UserInfoSqlConstants.GET_APP_LOGIN_ACCOUNT, beginDate, endDate);
		wap_login_account = jt.queryForInt(UserInfoSqlConstants.GET_WAP_LOGIN_ACCOUNT, beginDate, endDate);
		login_account = pc_login_account + app_login_account + wap_login_account;
		
		try{
			jt.update(UserInfoSqlConstants.LOGIN_INSERTSQL,pc_login_account,app_login_account,wap_login_account,login_account,statistical_date);
		}catch(Exception e){
			logger.info("批量处理插入失败，处理sql:"+UserInfoSqlConstants.LOGIN_INSERTSQL+"处理数据:"+statistical_date+"错误信息:"+e);
		}
				
		
		
	}
}
